package com.nativetalk.service.membsetmeal.insert;

import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.FoundChange.TdNtMembFoundChangeInset;
import com.nativetalk.bean.member.TdNtMember;
import com.nativetalk.bean.member.TdNtMemberInvite;
import com.nativetalk.bean.member.setmeal.TdNtMembSetmealInsert;
import com.nativetalk.bean.member.setmeal.TdNtMembSetmealList;
import com.nativetalk.bean.setmeal.TsNtSetmealDetail;
import com.nativetalk.common.Constants;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.util.CommonUtil;
import com.nativetalk.dao.TdNtMembFoundChangeDao;
import com.nativetalk.dao.TdNtMembSetmealDao;
import com.nativetalk.dao.TdNtMemberDao;
import com.nativetalk.dao.TsNtSetmealDao;
import com.pingplusplus.Pingpp;
import com.pingplusplus.model.Charge;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lizhun on 16/1/5.
 */
@Service
public class MembSetmealInsertServiceImpl implements MembSetmealInsertService {
    private static Logger logger = Logger.getLogger(MembSetmealInsertServiceImpl.class);
    @Resource
    private TdNtMembSetmealDao tdNtMembSetmealDao;
    @Resource
    private TsNtSetmealDao tsNtSetmealDao;
    @Resource
    private TdNtMembFoundChangeDao tdNtMembFoundChangeDao;
    @Resource
    private TdNtMemberDao tdNtMemberDao;
    @Override
    public RetInfo inserttdNtMembSetmeal(TdNtMember tdNtMember, String set_id, String userBlanace,String ip, String channel) {
        String logInfo = this.getClass().getName() + ":inserttdNtMembSetmeal:";
        logger.info("======" + logInfo + "begin======");
        Date now = new Date();
        RetInfo retInfo = new RetInfo();
        try {
            Map<String,Object> result = new HashMap<>();
            TsNtSetmealDetail tsNtSetmealDetail = tsNtSetmealDao.findTsNtSetmealDetail(Integer.valueOf(set_id));
            if (tsNtSetmealDetail != null) {
                Map<String,Integer> map = new HashMap<>();
                map.put("memb_id",tdNtMember.getMemb_id());
                map.put("set_id",Integer.valueOf(set_id));
                TdNtMembSetmealList tdNtMembSetmealList = tdNtMembSetmealDao.findTdNtMembSetmealBymembId(map);
                if (tdNtMembSetmealList == null) {
                    TdNtMembSetmealInsert tdNtMembSetmealInsert = new TdNtMembSetmealInsert();
                    tdNtMembSetmealInsert.setCou_id(tsNtSetmealDetail.getCou_id());
                    tdNtMembSetmealInsert.setEnd_time(new Timestamp(CommonUtil.getTime(tsNtSetmealDetail.getSet_type(),tsNtSetmealDetail.getSize())));
                    tdNtMembSetmealInsert.setMemb_id(tdNtMember.getMemb_id());
                    tdNtMembSetmealInsert.setMinute_amout(tsNtSetmealDetail.getSet_amout().divide(
                            new BigDecimal(tsNtSetmealDetail.getSet_time()),2, BigDecimal.ROUND_HALF_EVEN));
                    tdNtMembSetmealInsert.setOriginal_price(tsNtSetmealDetail.getOriginal_price());
                    tdNtMembSetmealInsert.setSet_amout(tsNtSetmealDetail.getSet_amout());
                    tdNtMembSetmealInsert.setSet_id(tsNtSetmealDetail.getSet_id());
                    tdNtMembSetmealInsert.setSet_limit(tsNtSetmealDetail.getSet_limit());
                    tdNtMembSetmealInsert.setSet_name(tsNtSetmealDetail.getSet_name());
                    tdNtMembSetmealInsert.setSet_synopis(tsNtSetmealDetail.getSet_synopis());
                    tdNtMembSetmealInsert.setSet_time(tsNtSetmealDetail.getSet_time());
                    tdNtMembSetmealInsert.setSet_type(tsNtSetmealDetail.getSet_type());
                    tdNtMembSetmealInsert.setState(Constants.SetMealPayState.unpaid);
                    tdNtMembSetmealInsert.setSurplus_time(tsNtSetmealDetail.getSet_time());
                    tdNtMembSetmealInsert.setSet_picture(tsNtSetmealDetail.getSet_picture());
                    tdNtMembSetmealInsert.setSize(tsNtSetmealDetail.getSize());
                    TdNtMembFoundChangeInset tdNtMembFoundChangeInset = new TdNtMembFoundChangeInset();
                    TdNtMemberInvite tdNtMemberInvite = new TdNtMemberInvite();
                    //判断是否使用余额
                    if (userBlanace.equals("0")) {
                        BigDecimal memb_balance = tdNtMemberDao.findTdNtMemberBalabce(tdNtMember.getMemb_id());

                        //判断余额是否足够
                        if (memb_balance.compareTo(tsNtSetmealDetail.getSet_amout()) > -1) {

                             memb_balance = memb_balance.subtract(tsNtSetmealDetail.getSet_amout());
                            tdNtMemberInvite.setMemb_balance(memb_balance);
                            tdNtMemberInvite.setMemb_id(tdNtMember.getMemb_id());
                            /**
                             * 添加资金变动记录
                             */
                            tdNtMembSetmealInsert.setState(Constants.SetMealPayState.un_end);

                            tdNtMembFoundChangeInset.setMemb_id(tdNtMember.getMemb_id());
                            tdNtMembFoundChangeInset.setMfchg_change_month(CommonUtil.getMonth(now));
                            tdNtMembFoundChangeInset.setMfchg_back_amount(memb_balance);
                            tdNtMembFoundChangeInset.setMfchg_change_amount(tsNtSetmealDetail.getSet_amout());
                            tdNtMembFoundChangeInset.setMfchg_change_name("购买课程");
                            tdNtMembFoundChangeInset.setMfchg_change_type(Constants.FundChangeType.wallet_out);
                            tdNtMembFoundChangeInset.setMfchg_front_amount(memb_balance.add(tsNtSetmealDetail.getSet_amout()));
                            tdNtMembFoundChangeInset.setState(Constants.PayState.success);
                            tdNtMembFoundChangeInset.setType(Constants.ChargeType.buy_course_code);
                            tdNtMembFoundChangeInset.setMfchg_number(CommonUtil.getOrderNub());

                            tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChangeInset);
                            /**
                             * 更新余额
                             */
                            tdNtMembSetmealInsert.setMfchg_id(tdNtMembFoundChangeInset.getMfchg_id());
                            tdNtMember.setMemb_balance(memb_balance);
                            tdNtMemberDao.updateTdNtMemberBalance(tdNtMemberInvite);
                        } else {
                            retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                            retInfo.setTip(ValidationMessages.getValue("MEMBBALANCE.NO"));
                            return  retInfo;
                        }

                    } else {
                        tdNtMembFoundChangeInset.setMemb_id(tdNtMember.getMemb_id());
                        tdNtMembFoundChangeInset.setMfchg_change_month(CommonUtil.getMonth(now));
                        tdNtMembFoundChangeInset.setMfchg_change_amount(tsNtSetmealDetail.getSet_amout());
                        tdNtMembFoundChangeInset.setMfchg_change_type(Constants.FundChangeType.wallet_out);
                        tdNtMembFoundChangeInset.setState(Constants.PayState.transfering);
                        tdNtMembFoundChangeInset.setType(Constants.ChargeType.buy_course_code);
                        tdNtMembFoundChangeInset.setMfchg_number(CommonUtil.getOrderNub());
                        if("alipay".equals(channel)){
                            //类型为支付宝支付
                            tdNtMembFoundChangeInset.setMfchg_change_name("支付宝购买课程");
                            tdNtMembFoundChangeInset.setMoney_change_type(Constants.PaymentChannel.alipay);
                        }
                        if("wx".equals(channel)){
                            //类型为微信支付
                            tdNtMembFoundChangeInset.setMfchg_change_name("微信购买课程");
                            tdNtMembFoundChangeInset.setMoney_change_type(Constants.PaymentChannel.wxpay);
                        }
                        Pingpp.apiKey = Constants.Live_Secret_Key;
                        Map<String, Object> chargeParams = new HashMap<String, Object>();
                        chargeParams.put("order_no",  tdNtMembFoundChangeInset.getMfchg_number());
                        //chargeParams.put("amount", 1);
                        chargeParams.put("amount", tdNtMembFoundChangeInset.getMfchg_change_amount().intValue()*100);  //单位为分
                        Map<String, String> app = new HashMap<String, String>();
                        app.put("id", Constants.APP_ID);
                        chargeParams.put("app",app);
                        chargeParams.put("channel",channel);  //微信wx
                        chargeParams.put("currency","cny");
                        chargeParams.put("client_ip",ip);
                        chargeParams.put("subject","外教君充值");
                        chargeParams.put("body","外教君充值");
                        Charge charge =   Charge.create(chargeParams);
                        result.put("charge",charge);
                        tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChangeInset);
                        tdNtMembSetmealInsert.setMfchg_id(tdNtMembFoundChangeInset.getMfchg_id());
                    }

                    tdNtMembSetmealDao.inserttdNtMembSetmeal(tdNtMembSetmealInsert);
                    /**
                     * 更新套餐购买人数
                     */
                    Map<String, Object> updateSetMeal = new HashMap<>();
                    tsNtSetmealDetail.setSize(tsNtSetmealDetail.getSet_size()+1);
                    updateSetMeal.put("set_id",tsNtSetmealDetail.getSet_id());
                    updateSetMeal.put("set_size",tsNtSetmealDetail.getSet_size());
                    tsNtSetmealDao.updateTsNtSetmealSize(updateSetMeal);

                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                    retInfo.setTip("够买成功");
                    retInfo.setObj(result);
                } else {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip(ValidationMessages.getValue("MEMB.SETMEAL.NOTNULL"));
                }
            } else {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip(ValidationMessages.getValue("SETMEAL.RESULT.NULL"));
            }
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(),e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }
}
